﻿using System;
using System.Configuration;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using Microsoft.Reporting.WinForms;
using System.IO;

namespace TMS
{
    public partial class WarehouseControl : UserControl
    {
        private bool warehouseListOfProdutsLoaded = false;
       
        Product prod = new Product();
        string[] row;
        DataTable table = new DataTable();
        DataSet data = new DataSet();
        bool init = false;
        string curentbarcode = "**";
        string curentPartNo = "";
        string curentProductName="";
        Categories cat = new Categories();
        Users ActivUser = Program.GetActiveUser;
        


        public WarehouseControl()
        {
            this.Cursor = Cursors.WaitCursor;
            if (!warehouseListOfProdutsLoaded)
            {
                warehouseListOfProdutsLoaded = true;
            }

            
            InitializeComponent();
            table = prod.GetAllJoinProductFromWarehouse();
            dgvWarehouseProductsList.DataSource = table;
            dgvWarehouseProductsList.Columns[0].HeaderText = "Бр. на Пр.";
            dgvWarehouseProductsList.Columns[1].HeaderText = "Име";
            dgvWarehouseProductsList.Columns[2].HeaderText = "Опис";
            dgvWarehouseProductsList.Columns[3].HeaderText = "Количина";
            dgvWarehouseProductsList.Columns[4].HeaderText = "Баркод";
            dgvWarehouseProductsList.Columns[4].Visible = false;

            dgvWarehouseProductsList.Columns[5].HeaderText = "Набавна цена";
            if (!ActivUser.Finance)
            dgvWarehouseProductsList.Columns[5].Visible = false;
            dgvWarehouseProductsList.Columns[5].DefaultCellStyle.Format = "N2";

            dgvWarehouseProductsList.Columns[6].Visible = false;
            dgvWarehouseProductsList.Columns[7].Visible = false;
            dgvWarehouseProductsList.Columns[8].Visible = false;
            dgvWarehouseProductsList.Columns[9].Visible = false;
            dgvWarehouseProductsList.Columns[10].Visible = false;
            dgvWarehouseProductsList.Columns[11].Visible = false;
            //ToStcmbWarehouses.ValueMember = "name";
            cmbCategory1.DisplayMember = "name";
            cmbCategory1.ValueMember = "id";
            cmbCategory2.DisplayMember = "name";
            cmbCategory2.ValueMember = "id";
            cmbCategory3.DisplayMember = "name";
            cmbCategory3.ValueMember = "id";
            cmbProductList.DisplayMember = "Name";
            cmbProductList.ValueMember = "Name";
            grbAddProduct.Visible = true;
            //dgvWarehouseProductsList.DataBindings.Clear();
            

            if (ActivUser.Finance)
               ToStTotalPrice.Visible = true;

            
            

            FillWharehouses();
            
            this.Cursor = Cursors.Default;
            Int32 i = 0;
            
           // dgvWarehouseProductsList.Rows[0].DefaultCellStyle.ForeColor = Color.Red;
            foreach (DataGridViewRow row in dgvWarehouseProductsList.Rows)
            {
                if (Convert.ToInt32(row.Cells[3].Value) < 0)
                {
                  //  MessageBox.Show(row.Cells[3].Value.ToString());
                    row.DefaultCellStyle.ForeColor = Color.Red;
                }
                i++;
            }

        }

        //private void loadWarehouseListOfProduts()
        //{
        //    this.Cursor = Cursors.WaitCursor;
        //    table = prod.GetAllProductsFromDB();
        //    this.Cursor = Cursors.Default;
        //}

        private void btnNewReceiveNote_Click(object sender, EventArgs e)
        {
            Program.GetMainForm.registerInHistoryMain(ControlsEnum.WAREHOUSE_CONTROL, null);

            this.Dispose();
            DataGridView tmp = new DataGridView();
            tmp.RowCount = 1;
            tmp.ColumnCount = 1;
            tmp.Rows[0].Cells[0].Value = 0;
            Program.GetMainForm.ShowControl(ControlsEnum.RECEIVE_NOTE_CONTROL,tmp.Rows[0]);
        }

        private void btnNewDispatchNote_Click(object sender, EventArgs e)
        {
            Program.GetMainForm.registerInHistoryMain(ControlsEnum.WAREHOUSE_CONTROL, null);

            this.Dispose();
            Program.GetMainForm.ShowControl(ControlsEnum.DISPATCH_NOTE_CONTROL);
        }

        

        private void cmbWarehouses_SelectedValueChanged(object sender, EventArgs e)
        {
            try
            {

                if (ToStcmbWarehouses.SelectedItem.ToString() != "сите")
                {
                    table = prod.GetAllJoinProductFromWarehouse(ToStcmbWarehouses.SelectedItem.ToString());
                }
                else
                table = prod.GetAllJoinProductFromWarehouse();
                dgvWarehouseProductsList.DataSource = table;
                dgvWarehouseProductsList.Update();
                dgvWarehouseProductsList.Columns[3].HeaderText = "Количина";
                rdbtnCategory1Search_CheckedChanged(sender, e);
                rdbtnCategory2Search_CheckedChanged(sender, e);
                rdbtnCategory3Search_CheckedChanged(sender, e);
                cmbProductList_SelectedValueChanged(sender, e);
                btnShowAll_Click(sender, e);
            }
            catch
            {
            }
           

           
        }

        public void FillWharehouses()
        {
            MySqlDataAdapter MyDA = new MySqlDataAdapter();
            DataSet table = new DataSet();
            string connString = ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;
            MySqlConnection mysqlCon = new MySqlConnection(connString);
            mysqlCon.Open();
            string sqlSelectAll = "SELECT * from warehouses";
            MyDA.SelectCommand = new MySqlCommand(sqlSelectAll, mysqlCon);
            MyDA.Fill(table);
            mysqlCon.Close();
            foreach (DataRow row in table.Tables[0].Rows)
            ToStcmbWarehouses.Items.Add(row.ItemArray[1].ToString()); 
            
        }

       

        

        private void txtBarcode_TextChanged(object sender, EventArgs e)
        {
            if (txtBarcode.Text.Length == 10)
            {
                dgvWarehouseProductsList.Rows.Clear();

                DataSet table = prod.GetProductByBarcode(txtBarcode.Text);
                DataSet prod1=new DataSet();
                

                foreach (DataRow Product in table.Tables[0].Rows)
                {
                    Int32 Quantity = Convert.ToInt32(Product.ItemArray[3]);
                    string warehouse = Product.ItemArray[2].ToString();
                    prod1 = prod.GetProductFromDBAsDataSet(Convert.ToInt32(Product.ItemArray[1]));
                    if (Quantity > 0)
                    {
                        prod1 = prod.GetProductFromDBAsDataSet(Convert.ToInt32(Product.ItemArray[1]));
                        row = new string[] { prod1.Tables[0].Rows[0].ItemArray[5].ToString(), prod1.Tables[0].Rows[0].ItemArray[4].ToString(), prod1.Tables[0].Rows[0].ItemArray[10].ToString(), warehouse, Quantity.ToString() };
                        dgvWarehouseProductsList.Rows.Add(row);
                    }
                    curentbarcode = txtBarcode.Text;
                    curentPartNo = prod1.Tables[0].Rows[0].ItemArray[5].ToString();
                    curentProductName = prod1.Tables[0].Rows[0].ItemArray[4].ToString();
                    
                }
                txtBarcode.Text = "";
            }
        }

        private void btnPrintBarcode_Click(object sender, EventArgs e)
        {
                rpvBarcode.Visible = true;
                ReportParameter Barcode = new ReportParameter("Barcode", "*"+curentbarcode+"*");
                ReportParameter PartNum = new ReportParameter("PartNum", curentPartNo);
                ReportParameter BarcodeNum = new ReportParameter("BarcodeNum", curentbarcode);
                ReportParameter ProductName = new ReportParameter("ProductName", curentProductName);
                this.rpvBarcode.LocalReport.SetParameters(Barcode);
                this.rpvBarcode.LocalReport.SetParameters(PartNum);
                this.rpvBarcode.LocalReport.SetParameters(BarcodeNum);
                this.rpvBarcode.LocalReport.SetParameters(ProductName);

                this.rpvBarcode.RefreshReport();
                this.rpvBarcode.PrinterSettings.PrinterName = "Brother Ql-700";
                System.Drawing.Printing.PageSettings pg=new System.Drawing.Printing.PageSettings();
                pg.Margins.Top = 20;
                pg.Margins.Bottom = 10;
                pg.Margins.Left = 10;
                pg.Margins.Right = 10;
                pg.Landscape = false;
                System.Drawing.Printing.PaperSize size = new System.Drawing.Printing.PaperSize();
                size.RawKind = (int)System.Drawing.Printing.PaperKind.Custom;
                pg.PaperSize = size;
                pg.PaperSize.Width = 240;
                pg.PaperSize.Height = 150;
                
                rpvBarcode.SetPageSettings(pg);
                byte[] byteViewer = rpvBarcode.LocalReport.Render("PDF");
                //FileStream  newFile = new FileStream();
                //newFile.Write(byteViewer, 0, byteViewer.Length);
                //newFile.Name = "test";
                //newFile.Close();
              
            
                //this.rpvBarcode.PageSetupDialog
            //this.rpvBarcode.LocalReport.
        }

        

        private void cmbCategory1_SelectedValueChanged(object sender, EventArgs e)
        {
            if (cmbCategory1.Items.Count == 0) cmbCategory1.DataSource = cat.GetAllCategory1().Tables[0];
            else
            {

                if (cmbCategory1.SelectedValue.ToString() == "1")
                {
                    cmbCategory2.DataSource = cat.GetAllCategory2("").Tables[0];
                    cmbCategory3.DataSource = cat.GetAllCategory3("", "").Tables[0];
                }
                else
                {
                    cmbCategory2.DataSource = cat.GetAllCategory2(cmbCategory1.SelectedValue.ToString()).Tables[0];
                    cmbCategory3.DataSource = cat.GetAllCategory3(cmbCategory1.SelectedValue.ToString(), "").Tables[0];
                    
                }
            }
            

        }

        private void cmbCategory2_SelectedValueChanged(object sender, EventArgs e)
        {

            if (cmbCategory2.Items.Count == 0) cmbCategory2.DataSource = cat.GetAllCategory2("").Tables[0];
            else
            {
                if (cmbCategory2.SelectedValue.ToString() == "1")
                {
                  //  cmbCategory3.DataSource = cat.GetAllCategory3("", "").Tables[0];
                }
                else
                {
                    cmbCategory3.DataSource = cat.GetAllCategory3("", cmbCategory2.SelectedValue.ToString()).Tables[0];
                   
                }
            }

        }

        private void cmbCategory3_SelectedValueChanged(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            if (cmbCategory3.Items.Count == 0) cmbCategory3.DataSource = cat.GetAllCategory3("", "").Tables[0];
            if (cmbCategory2.SelectedValue.ToString() != "System.Data.DataRowView")
                if (cmbCategory3.SelectedValue.ToString() != "System.Data.DataRowView")
                {

                    data = prod.GetProductFromDB(cmbCategory1.SelectedValue.ToString(), cmbCategory2.SelectedValue.ToString(), cmbCategory3.SelectedValue.ToString());
                    cmbProductList.Text = "";
                    cmbProductList.DataSource = data.Tables[0];
                   
                    cmbProductList.Update();
                }
            this.Cursor = Cursors.Default;

        }

        private void cmbProductList_SelectedValueChanged(object sender, EventArgs e)
        {
            dgvWarehouseProductsList.Update();
            if (radbtnNameSearch.Checked==true)
            if (cmbProductList.SelectedValue.ToString()!="System.Data.DataRowView")
            table.DefaultView.RowFilter = string.Format("Name ='"+ cmbProductList.SelectedValue.ToString()+"'");
            dgvWarehouseProductsList.Update();
        }

        

        private void btnShowAll_Click(object sender, EventArgs e)
        {
            table.DefaultView.RowFilter = string.Format("Name LIKE '%'");
            dgvWarehouseProductsList.Update();
        }

        private void dgvWarehouseProductsList_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (ActivUser.Finance)
            Program.GetMainForm.ShowControl(ControlsEnum.EDIT_WAREHOUSE_PRODUCTS_CONTROL, dgvWarehouseProductsList.CurrentRow);
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == Keys.Escape) this.Dispose();
            return base.ProcessCmdKey(ref msg, keyData);
        }

        private void BtnTotalPrice_Click(object sender, EventArgs e)
        {
            Decimal Totalprice = 0;
            Int32 i=0;
            foreach (DataRow row in table.Rows)
            {
                try
                {
                    Totalprice += Convert.ToDecimal(row.ItemArray[3]) * Convert.ToDecimal(row.ItemArray[5]);
                }
                catch
                {
                }

            }
            MessageBox.Show(Totalprice.ToString("N2"));
            

           // rpvBarcode.Reset();
           // rpvBarcode.Visible = true;
           // rpvBarcode.LocalReport.ReportPath = @"StocktakingWithPriceReport.rdlc";
            
           // StocktakingReportDataSet ds = new StocktakingReportDataSet();
           // foreach (DataGridViewRow row in dgvWarehouseProductsList.Rows)
           // {
           //     try
           //     {
           //         if (Convert.ToInt32(row.Cells[3].Value) > 0)
           //         {
           //             i++;
           //             dgvWarehouseProductsList.Visible = false;
           //             ds.Tables[0].Rows.Add(new object[] { i.ToString(), row.Cells[0].Value.ToString(), row.Cells[1].Value.ToString(), row.Cells[2].Value.ToString(), "x", row.Cells[3].Value.ToString(), "x", Convert.ToDecimal(row.Cells[5].Value).ToString("N2"), (Convert.ToDecimal(row.Cells[3].Value) * Convert.ToDecimal(row.Cells[5].Value)).ToString("N2") });
           //         }
           //     }
           //     catch
           //     {
           //     }
                
           // }
           // rpvBarcode.RefreshReport();
           // ReportParameter Date = new ReportParameter("Date", DateTime.Today.ToString("dd-MM-yyyy"));
           // ReportParameter Price = new ReportParameter("TotalPrice", Totalprice.ToString("N2"));
           // ReportParameter User = new ReportParameter("ActiveUser",ActivUser.GetName()+" "+ActivUser.GetSurname());
           //// ReportParameter PartnerPar = new ReportParameter("Partner", PartnerName);
           //// ReportParameter PartnerAddressPar = new ReportParameter("PartnerAdress", PartnerAddress);
           // ReportDataSource rds = new ReportDataSource("DS1", ds.Tables[0]);
           // this.rpvBarcode.LocalReport.DataSources.Add(rds);
           // this.rpvBarcode.LocalReport.SetParameters(Price);
           // this.rpvBarcode.LocalReport.SetParameters(Date);

           //// this.rpvStocktakingReport.LocalReport.SetParameters(NNumber);
           //// this.rpvStocktakingReport.LocalReport.SetParameters(PartnerPar);
           //// this.rpvStocktakingReport.LocalReport.SetParameters(PartnerAddressPar);
           // this.rpvBarcode.RefreshReport();
        }

        private void dgvWarehouseProductsList_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            Int32 i = 0;

            // dgvWarehouseProductsList.Rows[0].DefaultCellStyle.ForeColor = Color.Red;
            foreach (DataGridViewRow row in dgvWarehouseProductsList.Rows)
            {
                if (Convert.ToInt32(row.Cells[3].Value) < 0)
                {
                    //  MessageBox.Show(row.Cells[3].Value.ToString());
                    row.DefaultCellStyle.ForeColor = Color.Red;
                }
                else if (Convert.ToInt32(row.Cells[3].Value) < Convert.ToInt32(row.Cells[8].Value))
                {
                    //  MessageBox.Show(row.Cells[3].Value.ToString());
                    row.DefaultCellStyle.ForeColor = Color.DarkCyan;
                }
                i++;
            }
        }

        private void dgvWarehouseProductsList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if ((dgvWarehouseProductsList.CurrentCell.ColumnIndex==3)&&(e.RowIndex!=-1))
            MessageBox.Show("Минимална залиха "+dgvWarehouseProductsList.CurrentRow.Cells[8].Value.ToString());
        }

        private void rdbtnCategory1Search_CheckedChanged(object sender, EventArgs e)
        {
            if (rdbtnCategory1Search.Checked == true)
                table.DefaultView.RowFilter = string.Format("Category_1 ='" + cmbCategory1.SelectedValue.ToString() + "'");
            dgvWarehouseProductsList.Update();
        }

        private void rdbtnCategory2Search_CheckedChanged(object sender, EventArgs e)
        {
            if (rdbtnCategory2Search.Checked == true)
                table.DefaultView.RowFilter = string.Format("Category_2 ='" + cmbCategory2.SelectedValue.ToString() + "'");
            dgvWarehouseProductsList.Update();
        }

        private void rdbtnCategory3Search_CheckedChanged(object sender, EventArgs e)
        {
            if (rdbtnCategory3Search.Checked == true)
                table.DefaultView.RowFilter = string.Format("Category_3 ='" + cmbCategory3.SelectedValue.ToString() + "'");
            dgvWarehouseProductsList.Update();
        }

        private void toolStocktaking_Click(object sender, EventArgs e)
        {
            this.Hide();
            Program.GetMainForm.ShowControl(ControlsEnum.STOCKTAKING_CONTROL);
        }
        private void ToStBack_Click(object sender, EventArgs e)
        {
            if (Program.GetMainForm.Back())
                this.Dispose();
        }


        private void ToStForward_Click(object sender, EventArgs e)
        {
            if (Program.GetMainForm.Forward())
                this.Dispose();
        }

        }

    
       

}
